﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
  
    public Transform hammerHead;
    public Transform body;
    private Rigidbody2D playrig;
    public float maxRange = 2.0f;
    // Start is called before the first frame update
    void Start()
    {
        Physics2D.IgnoreCollision(hammerHead.GetComponent<Collider2D>(), body.GetComponent<Collider2D>());
        playrig = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        float depth = Mathf.Abs(Camera.main.transform.position.z);
        Vector3 center = new Vector3(Screen.width / 2, Screen.height / 2, depth);
        Vector3 mouse = new Vector3(Input.mousePosition.x, Input.mousePosition.y, depth);
        center = Camera.main.ScreenToWorldPoint(center);
        mouse = Camera.main.ScreenToWorldPoint(mouse);
        Vector3 mouseVec = Vector3.ClampMagnitude(mouse - center, maxRange);
        hammerHead.GetComponent<Rigidbody2D>().MovePosition(body.position + mouseVec);
        ContactFilter2D contactFilter = new ContactFilter2D();
        contactFilter.useLayerMask = true;
        contactFilter.layerMask = LayerMask.GetMask("Default");
        Collider2D[] results = new Collider2D[5];
        if (hammerHead.GetComponent<Rigidbody2D>().OverlapCollider(contactFilter, results) > 0)
        {
            Vector3 targetBodyPos = hammerHead.position - mouseVec;
            Vector3 force = (targetBodyPos - body.position) * 40.0f;
            Debug.DrawLine(body.position, body.position + force);
            body.GetComponent<Rigidbody2D>().AddForce(force);
        }
        if (Input.GetKey(KeyCode.A))
        {
            maxRange = 4.0f;
        }
        if (Input.GetKey(KeyCode.S))
        {
            maxRange = 6.0f;
        }
        if (Input.GetKey(KeyCode.D))
        {
            maxRange = 8.0f;
        }

        if (Input.GetKey(KeyCode.E))//&&Xing.score>=2
        {
            playrig.velocity = new Vector2(playrig.velocity.x+3, playrig.velocity.y);
        }
        if (Input.GetKey(KeyCode.W))//&&Xing.score >= 2
        {
            playrig.velocity = new Vector2(playrig.velocity.x -3, playrig.velocity.y);
        }
    }
}
